import "./shopping.css"
import { Checkbox, Divider, Space, Button, Radio, message, Modal, Avatar } from 'antd';
import { useNavigate, NavLink } from "react-router-dom"
import { useState, useEffect } from 'react';
import {
    getCartList,
    getCartAdd,
    getCartRemove,
    getCartDelete,
} from "../../tools/ajax"
import { PlusOutlined, MinusOutlined, DeleteOutlined, ExclamationCircleFilled, LoadingOutlined } from "@ant-design/icons"


export default () => {
    const CheckboxGroup = Checkbox.Group;
    const [messageApi, contextHolder] = message.useMessage();

    const plainOptions = ['Apple', 'Pear', 'Orange'];
    const defaultCheckedList = ['Apple', 'Orange'];
    const [size, setSize] = useState('large');;
    const [throttle, setThrottle] = useState(true);;
    const [checkedAll, setCheckedAll] = useState(false);;

    const [checkList, setCheckList] = useState([]);
    const [carList, setCarList] = useState([]);
    const [checkedList, setCheckedList] = useState(defaultCheckedList);
    const [indeterminate, setIndeterminate] = useState(true);
    const [checkAll, setCheckAll] = useState(false);
    const [isIndeterminate, setIsIndeterminate] = useState(false);

    const navigate = useNavigate()

    const { confirm } = Modal;


    const onChange = (list) => {
        setCheckedList(list);
        setIndeterminate(!!list.length && list.length < plainOptions.length);
        setCheckAll(list.length === plainOptions.length);
    };
    const onCheckAllChange = (e) => {
        setCheckedList(e.target.checked ? plainOptions : []);
        setIndeterminate(false);
        setCheckAll(e.target.checked);
    };


    const getShopCarData = () => {
        getCartList({ token: sessionStorage.getItem('setToken') }).then((res) => {
            console.log("请求数据", res);
            setCarList([...res.data]);
        })
    }


    // 同一处理删改的响应结果
    const disposeRes = (res) => {
        if (res.code == 0) {
            messageApi.open({
                type: 'warning',
                content: '登录过期,要去登录页喽~~',
            });
            setTimeout(() => {
                navigate("/login");
            }, 2000);
        } else if (res.code == 1) {
            console.log("2222222222222");
            // 服务器修改成功后,重新请求购物车数据
            getShopCarData();
            messageApi.open({
                type: 'success',
                content: '商品数量修改成功,还待是你小子',
            });
        } else {
            messageApi.open({
                type: 'error',
                content: '购物操作失败喽,请喝会儿茶休息一下吧',
            });
        }
    }


    // 增加商品数量
    const addGoods = (id) => {
        console.log("点击了", id);
        if (throttle) {
            getCartAdd({
                goodId: id,
                token: sessionStorage.getItem('setToken'),
            }).then((res) => {
                // 使用公共函数统一处理响应结果
                console.log("11111111", res.data);
                disposeRes(res.data);
            });
            setTimeout(() => {
                setThrottle(true)
            }, 600)
        } else {
            messageApi.open({
                type: 'warning',
                content: '少爷不要点太快啦,老奴都算不过来啦/(ㄒoㄒ)/~~',
            });

        }
        setThrottle(false)
    }

    // 减少商品数量
    const removeGoods = (id, i) => {
        if (throttle) {
            if (carList[i].count <= 1) {
                alert("少爷不能在少啦/(ㄒoㄒ)/~~");
                return
            }
            getCartRemove({
                goodId: id,
                token: sessionStorage.getItem('setToken'),
            }).then((res) => {
                disposeRes(res.data)
            });
            setTimeout(() => {
                setThrottle(true)
            }, 600)
        } else {
            messageApi.open({
                type: 'warning',
                content: '少爷不要点太快啦,老奴都算不过来啦/(ㄒoㄒ)/~~',
            });
        }
        setThrottle(false)

    }

    const deleteGoods = (id) => {
        confirm({
            title: '真的要删除宝贝吗?老奴于心不忍呀/(ㄒoㄒ)/~~',
            icon: <ExclamationCircleFilled />,
            content: '少爷三思~',
            okText: '少爷的规矩就是规矩!',
            okType: 'danger',
            cancelText: '那本少再考虑考虑',
            maskClosable: "true",
            width: 540,
            onOk() {
                console.log('OK');
                // then函数是点击确定执行的回调函数，在这里执行删除操作
                getCartDelete({
                    goodId: id,
                    token: sessionStorage.getItem('setToken'),
                }).then((res) => {
                    disposeRes(res.data);
                });
                // 清理选中列表中的这个商品id
                checkList.forEach((item, i) => {
                    if (item == id) {

                        setCheckList([...checkList.splice(i, 1)]);
                    }
                });
                checkChange();


            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }



    // 判断全选状态
    const checkChange = () => {
        console.log("判断", checkList, carList);

        // 全选
        if (checkList.length == carList.length) {
            setCheckedAll(true);
            setIsIndeterminate(false);
        }

        // 全不选
        else if (checkList.length == 0) {
            setCheckedAll(false);
            setIsIndeterminate(false);
        }

        // 选中一部分
        else {
            setIsIndeterminate(true);
        }
        console.log(checkedAll);
    }

    const pay = () => {
        console.log("少爷快快赏钱");
        console.log("222222222", checkList);

        // 异步弹出框
        confirm({
            title: '真的要全部拿下吗?老奴感谢少爷恩典~~',
            icon: <ExclamationCircleFilled />,
            content: '大手一挥,统统拿下',
            okText: '少爷的规矩就是规矩!',
            okType: 'danger',
            cancelText: '那本少再考虑考虑',
            maskClosable: "true",
            width: 540,
            onOk() {
                console.log('OK');
                checkList.forEach((payItem, id) => {
                    // then函数是点击确定执行的回调函数，在这里执行删除操作
                    getCartDelete({
                        goodId: payItem,
                        token: sessionStorage.getItem('setToken'),
                    }).then((res) => {
                        // this.disposeRes();
                        res = res.data;

                        if (res.code == 0) {
                            messageApi.open({
                                type: 'warning',
                                content: '登录过期,要去登录页喽~~',
                            });
                            setTimeout(() => {
                                navigate("/login");
                            }, 2000);
                        } else if (res.code == 1) {
                            console.log("2222222222222");
                            // 服务器修改成功后,重新请求购物车数据
                            getShopCarData();
                            messageApi.open({
                                type: 'success',
                                content: '购买成功,少爷大气',
                            });
                        } else {
                            messageApi.open({
                                type: 'error',
                                content: '购物操作失败喽,请喝会儿茶休息一下吧',
                            });
                        }
                    });
                    // 清理选中列表中的这个商品id

                    if (payItem == id) {
                        setCheckList([...checkList.splice(i, 1)]);
                    }

                    checkChange();
                })


            },
            onCancel() {
                console.log('Cancel');
            },
        });



    }

    useEffect(() => {
        getShopCarData()
    }, [])

    if (carList.length) {
        return (
            <div className="shopping_box">
                <h1>购物车</h1>
                {contextHolder}
                <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
                    全选
                </Checkbox>
                <Divider />
                <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />




                <ul className="goodsList">

                    {
                        carList.map((item, i) => {
                            return (<li key={item.Id}>
                                <Checkbox onChange={checkChange}></Checkbox>

                                <img src={item.imageUrl} alt="" />
                                <h3>{item.title}</h3>
                                <div>
                                    <b className="price">￥{item.priceStr}</b>
                                    <br />
                                    <PlusOutlined style={{ backgroundColor: '#0e0e0e', borderRadius: "50%", padding: "4px", color: '#fefefe' }} className="el-icon-circle-plus" onClick={() => { addGoods(item.Id) }} />
                                    &emsp;&emsp; <span className="count">{item.count}</span>&emsp;&emsp;
                                    <MinusOutlined style={{ backgroundColor: '#0e0e0e', borderRadius: "50%", padding: "4px", color: '#fefefe' }} className="el-icon-remove" onClick={() => { removeGoods(item.Id, i) }} />

                                </div>
                                <Button className="" type="primary" block danger shape="circle" icon={<DeleteOutlined />} size={size} onClick={() => { deleteGoods(item.Id) }} />
                            </li>)
                        })
                    }

                </ul>




                <div className="pay">
                    <div className="pay_content">
                        <b>总计: {800} 元</b>

                        <Button type="primary" onClick={pay} >
                            结算
                        </Button>
                    </div>
                </div>
            </div>
        )
    } else {
        return (
            <div className="kong"  >
                <LoadingOutlined />

                购物车空空如也
                <Button type="primary">
                    <NavLink to={"/"}>随便逛逛</NavLink>
                </Button>



            </div>
        )

    }

}